<template>
  <div class="audio-player fill">
    <audio
      ref="audio"
      @timeupdate="handlePlaying"
      @canplay="canplay"
      @pause="playing=false"
      @play="playing=true"
      @waiting="handleWaiting"
      :src="src"></audio>

    <div class="controls">
      <div class="play-bar"  ref="playBar" @click="handleChangeCurrent">
        <div class="total-width fill"/>
        <div class="current-width h-fill" :style="{width: currentWidth}"/>
        <div
          @mousedown="handleMoveStart"
          ref="playPoint"
          class="current-point"
          :style="{left: currentWidth}"/>
      </div>
      <div class="info-bar flex-row items-center justify-center">
        <div class="songInfo">123</div>
        <div class="btn-bar flex-row items-center">
          <div class="btn">
            <WIcon icon="icon-backward" size="22" color="blue"/>
          </div>
          <div  class="play flex-center btn" @click="togglePlay">
            <WIcon v-if="playing" icon="icon-pause" size="22" color="blue"/>
            <WIcon v-else icon="icon-play" size="22" color="blue"/>
          </div>
          <div class="btn">
            <WIcon icon="icon-forward" size="22" color="blue"/>
          </div>
        </div>
        <div class="timeInfo flex-row items-center">
          <div class="timearea flex-row">
            <div class="time">{{current|timeFilter}}</div>/
            <div class="time">{{total|timeFilter}}</div>
          </div>

          <div class="btn">
            <WIcon v-if="mode===0" icon="icon-3" color="blue"/>
            <WIcon v-if="mode===1" icon="icon-danqu" color="blue"/>
            <WIcon v-if="mode===2" icon="icon-suiji" color="blue"/>
          </div>
          <WIcon icon="icon-table"/>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import WIcon from "@/components/icon/WIcon"
import {fileApi} from "@/api/table/file"
export default {
  name: "AudioPlayer",
  components: {WIcon},
  data: () => ({
    player: null,
    init: false,  // 是否被初始化过
    current: 0,  // 当前时间
    onMove: false,  // 是否在移动中
    mode: 0,  // 0/1/2 列表循环  1单一循环  2随机播放
    playList: [],
    index: 0,
    playing: false,
  }),
  computed: {
    total() {
      return this.playing ? this.player.duration : 0
    },
    currentWidth() {
      return (this.current / this.total * 100).toFixed(2) + "%"
    },
    src() {
      return this.playList.length ? this.playList[this.index].content : ""
    }
  },
  filters:{
    timeFilter(time){
      let second, minute
      minute = parseInt(time / 60)
      second = time - minute * 60
      minute = minute.toFixed(0).padStart(2, "0")
      second = second.toFixed(0).padStart(2, "0")
      return `${minute}:${second}`
    }
  },
  mounted() {
    this.player = this.$refs.audio
    window.a = this.player
  },
  methods: {
    handleWaiting() {
      this.loading = this.$loading()
    },
    canplay() {
      if(this.loading){
        this.loading.close()
      }
      this.init = true
      this.player.play().catch(err=>{
        console.log(err)
      })
    },
    handlePlaying(e) {
      if (this.init && !this.onMove) {
        this.current = e.target.currentTime
      }
    },
    // 点选
    handleChangeCurrent(e) {
      if(e.target===this.$refs.playPoint || this.onMove){
        return
      }
      let barWidth = this.$refs.playBar.clientWidth
      let offsetX = e.offsetX
      let totalX = barWidth
      let percent = offsetX / totalX
      this.player.currentTime = this.total * percent
    },
    // 移动
    handleMoveStart(e) {
      let barWidth = this.$refs.playBar.clientWidth
      let target =  this.$refs.playPoint
      this.onMove = true
      let startX = e.x
      let offsetX = target.offsetLeft
      let moveHandler = e => {
        let delta = e.x - startX
        let endX =  offsetX + delta
        endX = Math.max(endX, 0)
        endX = Math.min(endX, barWidth)
        let percent = endX / barWidth
        this.current = this.total * percent
        target.style.left = percent * 100 + "%"
      }
      let mouseUpHandler = () => {
        let percent = target.offsetLeft / barWidth
        this.player.currentTime = this.total * percent
        this.onMove = false
        window.removeEventListener("mousemove", moveHandler)
        window.removeEventListener("mouseup", mouseUpHandler)
      }
      window.addEventListener("mousemove", moveHandler)
      window.addEventListener("mouseup", mouseUpHandler)
    },
    // 播放暂停点击
    togglePlay() {
      if(!this.player){
        this.$msg.warning("等待播放器初始化")
      }
      if(this.playing){
        this.player.pause()
      }else{
        this.player.play()
      }
    },
    onReceiveMsg(from, {album, songID}){
      this.fetchAlbum(album.id, songID)
    },
    async fetchAlbum(id, songID) {
      let loading = this.$loading()
      fileApi.getAll({parent: id}).then(ret=>{
        loading.close()
        this.playList = ret.data
        if(ret.code===0){
          this.playList = ret.data
          if(songID){
            this.index = this.playList.findIndex(ret=> ret.id ===songID)
            this.canplay()
          }
        }
      })
    },
    setPlayList(playlist, index) {
      this.playList = playlist
      this.index = index
    }
  }
}
</script>

<style scoped lang="scss">
@import "~@/assets/css/var";
.audio-player {
  position: relative;
  user-select: none;
}

.controls {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  background-color: #E4E7ED;
  height: 80px;

  .play-bar {
    margin: 10px auto;
    width: 90%;
    height: 10px;
    position: relative;
    cursor: pointer;
    //border: 1px solid red;
    .total-width {
      position: absolute;
      background-color: white;
      cursor: pointer;
    }

    .current-width{
      position: absolute;
      background-color: red;
      width: 0;
    }

    .current-point{
      position: absolute;
      width: 15px;
      height: 15px;
      top: 50%;
      border-radius: 50%;
      background-color: blueviolet;
      border: 1px solid white;
      transform: translate(-50%, -50%);
      cursor: pointer;
    }
  }
  .info-bar{
    position: relative;
    .btn-bar{
      .btn{
        cursor: pointer;
        margin: 0 $mn;
      }
      .play{
        background-color: #29e7fe;
        padding: 10px;
        border-radius: 50%;
      }
    }
    .songInfo{
      position: absolute;
      padding-left: $pl;
      left: 0;
    }
    .timeInfo{
      position: absolute;
      right: 0;
      padding-right: $pl;
      &>*{
        margin: $mn;
      }
      .timearea{
        color: $text-info;
      }
    }
  }
}
</style>
